<template>
  <div class="item-browse">
    <!-- 页面标题和搜索 -->
    <div class="page-header">
      <div class="header-content">
    <h2>物品浏览</h2>
        <p>查看可回收物品和当前价格</p>
      </div>
      <div class="search-section">
        <el-input
          v-model="searchKeyword"
          placeholder="搜索物品名称..."
          size="large"
          style="width: 300px;"
          @input="handleSearch"
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>
      </div>
    </div>

    <!-- 筛选器 -->
    <el-card class="filter-card" shadow="never">
      <div class="filters">
        <div class="filter-group">
          <label>分类筛选：</label>
          <el-select
            v-model="selectedCategory"
            placeholder="全部分类"
            clearable
            style="width: 150px"
            @change="handleCategoryChange"
          >
            <el-option
              v-for="category in categories"
              :key="category.id"
              :label="category.name"
              :value="category.id"
            />
          </el-select>
        </div>
        
        <div class="filter-group">
          <label>价格排序：</label>
          <el-select
            v-model="priceSort"
            placeholder="默认排序"
            clearable
            style="width: 150px"
            @change="handleSortChange"
          >
            <el-option label="价格从高到低" value="desc" />
            <el-option label="价格从低到高" value="asc" />
          </el-select>
        </div>

        <div class="filter-group">
          <label>状态筛选：</label>
          <el-select
            v-model="statusFilter"
            placeholder="全部状态"
            clearable
            style="width: 150px"
            @change="handleStatusChange"
          >
            <el-option label="可回收" value="active" />
            <el-option label="暂停回收" value="inactive" />
          </el-select>
        </div>

        <el-button type="primary" @click="resetFilters">
          <el-icon><Refresh /></el-icon>
          重置筛选
        </el-button>
      </div>
    </el-card>

    <!-- 物品列表 -->
    <div class="items-section">
      <el-row :gutter="20">
        <el-col
          v-for="item in paginatedItems"
          :key="item.id"
          :xs="24"
          :sm="12"
          :md="8"
          :lg="6"
          :xl="6"
        >
          <el-card class="item-card" shadow="hover">
            <div class="item-image">
              <img 
                :src="item.image || '/default-item.jpg'" 
                :alt="item.name"
                @error="handleImageError"
              />
              <div class="item-status" :class="item.status">
                {{ item.status === 'active' ? '可回收' : '暂停回收' }}
              </div>
            </div>
            
            <div class="item-info">
              <h3 class="item-name">{{ item.name }}</h3>
              <p class="item-category">{{ getCategoryName(item.category) }}</p>
              <p class="item-description">{{ item.description }}</p>
              
              <div class="item-price-info">
                <div class="price-section">
                  <span class="price">¥{{ item.pricePerUnit }}</span>
                  <span class="unit">/{{ item.unit }}</span>
                </div>
                <div class="price-trend" v-if="item.priceTrend">
                  <el-icon 
                    :color="item.priceTrend === 'up' ? '#67C23A' : '#F56C6C'"
                  >
                    <ArrowUp v-if="item.priceTrend === 'up'" />
                    <ArrowDown v-else />
                  </el-icon>
                  <span :class="item.priceTrend">
                    {{ item.priceChange }}%
                  </span>
                </div>
              </div>

              <div class="item-actions">
                <el-button 
                  type="primary" 
                  size="small"
                  @click.stop="addToOrder(item)"
                  :disabled="item.status !== 'active'"
                >
                  <el-icon><Plus /></el-icon>
                  添加到订单
                </el-button>
                <el-button 
                  type="info" 
                  size="small" 
                  plain
                  @click.stop="viewRecycleGuide(item)"
                >
                  回收指南
                </el-button>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>

      <!-- 空状态 -->
      <el-empty 
        v-if="filteredItems.length === 0" 
        description="暂无符合条件的物品"
        :image-size="200"
      />
    </div>

    <!-- 分页 -->
    <div class="pagination-section" v-if="filteredItems.length > 0">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[12, 24, 36, 48]"
        :total="filteredItems.length"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 回收指南对话框 -->
    <el-dialog
      v-model="recycleGuideVisible"
      :title="`${selectedRecycleItem?.name} - 回收指南`"
      width="700px"
      @close="recycleGuideVisible = false"
    >
      <div v-if="selectedRecycleItem" class="recycle-guide">
        <el-card class="guide-section" shadow="never">
          <template #header>
            <div class="section-title">
              <el-icon color="#409EFF"><InfoFilled /></el-icon>
              <span>回收要求</span>
        </div>
          </template>
          <p class="guide-content">{{ selectedRecycleItem.requirements || '无特殊要求，保持物品干净整洁即可。' }}</p>
        </el-card>

        <el-card class="guide-section" shadow="never">
          <template #header>
            <div class="section-title">
              <el-icon color="#67C23A"><CircleCheck /></el-icon>
              <span>处理步骤</span>
          </div>
          </template>
          <div class="guide-steps">
            <div v-for="(step, index) in getRecycleSteps(selectedRecycleItem)" :key="index" class="step-item">
              <div class="step-number">{{ index + 1 }}</div>
              <div class="step-content">{{ step }}</div>
          </div>
          </div>
        </el-card>

        <el-card class="guide-section" shadow="never">
          <template #header>
            <div class="section-title">
              <el-icon color="#E6A23C"><Warning /></el-icon>
              <span>注意事项</span>
          </div>
          </template>
          <ul class="notice-list">
            <li v-for="(notice, index) in getRecycleNotices(selectedRecycleItem)" :key="index">
              {{ notice }}
            </li>
          </ul>
        </el-card>

        <el-card class="guide-section" shadow="never">
          <template #header>
            <div class="section-title">
              <el-icon color="#909399"><Document /></el-icon>
              <span>回收价值</span>
          </div>
          </template>
          <div class="recycle-value">
            <p>{{ getRecycleValue(selectedRecycleItem) }}</p>
            <div class="price-info">
              <span>当前回收价：</span>
              <span class="price">¥{{ selectedRecycleItem.pricePerUnit }}/{{ selectedRecycleItem.unit }}</span>
        </div>
          </div>
        </el-card>
      </div>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="recycleGuideVisible = false">关闭</el-button>
          <el-button 
            type="primary" 
            @click="addToOrderFromGuide"
            :disabled="selectedRecycleItem?.status !== 'active'"
          >
            <el-icon><Plus /></el-icon>
            添加到订单
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { useRouter } from 'vue-router'
import { useStore } from 'vuex'
import {
  Search,
  Refresh,
  Plus,
  ArrowUp,
  ArrowDown,
  InfoFilled,
  CircleCheck,
  Warning,
  Document
} from '@element-plus/icons-vue'
import { itemsAPI } from '@/api'

// 组件名称
defineOptions({
  name: 'ItemBrowse'
})

const router = useRouter()
const store = useStore()

// 响应式数据
const loading = ref(false)
const searchKeyword = ref('')
const selectedCategory = ref('')
const priceSort = ref('')
const statusFilter = ref('')
const currentPage = ref(1)
const pageSize = ref(12)

// 对话框状态
const recycleGuideVisible = ref(false)
const selectedRecycleItem = ref(null)

// 数据
const items = ref([])
const categories = ref([])

// 内嵌模拟数据已删除，统一使用 API 数据

// 计算属性
const filteredItems = computed(() => {
  let result = [...items.value]

  // 关键词搜索
  if (searchKeyword.value) {
    const keyword = searchKeyword.value.toLowerCase()
    result = result.filter(item =>
      item.name.toLowerCase().includes(keyword) ||
      (item.description && item.description.toLowerCase().includes(keyword))
    )
  }

  // 分类筛选
  if (selectedCategory.value) {
    result = result.filter(item => item.category === selectedCategory.value)
  }

  // 状态筛选
  if (statusFilter.value) {
    result = result.filter(item => item.status === statusFilter.value)
  }

  // 价格排序
  if (priceSort.value) {
    result.sort((a, b) => {
      const priceA = typeof a.pricePerUnit === 'number' ? a.pricePerUnit : parseFloat(a.pricePerUnit) || 0
      const priceB = typeof b.pricePerUnit === 'number' ? b.pricePerUnit : parseFloat(b.pricePerUnit) || 0
      return priceSort.value === 'desc' 
        ? priceB - priceA
        : priceA - priceB
    })
  }

  return result
})

const paginatedItems = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return filteredItems.value.slice(start, end)
})

// 方法
const loadItems = async () => {
  try {
    loading.value = true
    const response = await itemsAPI.getItems({
      page: 1,
      pageSize: 1000,
      status: '' // 获取所有状态的物品
    })
    
    const itemList = response.list || response.data || response || []
    items.value = itemList
    
    // 加载物品后，从物品列表中提取分类
    loadCategories()
  } catch (error) {
    console.error('加载物品列表失败:', error)
    ElMessage.error('连接服务器失败，请稍后重试')
    items.value = []
  } finally {
    loading.value = false
  }
}

const loadCategories = () => {
  try {
    // 从物品列表中提取唯一的分类
    const uniqueCategories = [...new Set(items.value.map(item => item.category))]
    categories.value = uniqueCategories.map(cat => ({
      id: cat,
      name: cat
    }))
  } catch (error) {
    console.error('加载分类失败:', error)
    categories.value = []
  }
}

const getCategoryName = (categoryName) => {
  // 直接返回分类名称，因为后端存储的就是分类名称字符串
  return categoryName || '未知分类'
}

const handleSearch = () => {
  currentPage.value = 1
}

const handleCategoryChange = () => {
  currentPage.value = 1
}

const handleSortChange = () => {
  currentPage.value = 1
}

const handleStatusChange = () => {
  currentPage.value = 1
}

const resetFilters = () => {
  searchKeyword.value = ''
  selectedCategory.value = ''
  priceSort.value = ''
  statusFilter.value = ''
  currentPage.value = 1
}

const handleSizeChange = (newSize) => {
  pageSize.value = newSize
  currentPage.value = 1
}

const handleCurrentChange = (newPage) => {
  currentPage.value = newPage
}

const addToOrder = (item) => {
  // 检查物品状态
  if (item.status !== 'active') {
    ElMessage.warning(`${item.name} 已暂停回收，无法添加到订单`)
    return
  }
  
  // 转换物品数据格式以匹配 CreateOrder 页面的格式
  const cartItem = {
    id: item.id,
    name: item.name,
    category: item.category,
    unit: item.unit,
    price: item.pricePerUnit,
    description: item.description,
    image: item.image,
    status: item.status
  }
  
  // 添加到购物车
  store.commit('ADD_TO_CART', cartItem)
  
  ElMessage.success({
    message: `已添加 ${item.name} 到订单`,
    duration: 1500
  })
  
  // 跳转到创建订单页面
  setTimeout(() => {
    router.push('/customer/create-order')
  }, 500)
}

const viewRecycleGuide = (item) => {
  selectedRecycleItem.value = item
  recycleGuideVisible.value = true
}

const addToOrderFromGuide = () => {
  if (selectedRecycleItem.value) {
    if (selectedRecycleItem.value.status === 'active') {
      addToOrder(selectedRecycleItem.value)
      recycleGuideVisible.value = false
    } else {
      ElMessage.warning(`${selectedRecycleItem.value.name} 已暂停回收，无法添加到订单`)
    }
  }
}

const getRecycleSteps = (item) => {
  const categorySteps = {
    '纸类': [
      '清除纸张上的污渍和胶带',
      '将纸张按大小分类整理',
      '压平并捆扎整齐',
      '保持干燥存放'
    ],
    '塑料': [
      '清洗瓶内残留物',
      '撕去外包装标签',
      '压扁瓶身节省空间',
      '分类存放不同材质'
    ],
    '金属': [
      '清洁表面油污和杂质',
      '去除非金属附件',
      '按金属类型分类',
      '安全存放，避免锈蚀'
    ],
    '玻璃': [
      '清洗干净瓶内残留',
      '去除瓶盖和标签',
      '检查是否有裂痕',
      '分类存放，小心轻放'
    ],
    '电子产品': [
      '备份重要数据',
      '恢复出厂设置',
      '拆除电池等配件',
      '按设备类型分类'
    ],
    '有害垃圾': [
      '妥善包装，防止泄漏',
      '与其他垃圾分开存放',
      '标记清楚物品类型',
      '送至专门回收点'
    ]
  }
  
  return categorySteps[item.category] || [
    '检查物品状态',
    '清洁并整理',
    '分类存放',
    '联系回收站回收'
  ]
}

const getRecycleNotices = (item) => {
  const categoryNotices = {
    '纸类': [
      '不可回收沾有油污的纸张',
      '确保纸张干燥，潮湿会降低价值',
      '纸箱需要拆平，节省空间'
    ],
    '塑料': [
      '只接受PET材质塑料瓶',
      '瓶盖需单独分类',
      '清洗不彻底会影响回收价格'
    ],
    '金属': [
      '带有危险品残留的金属不可回收',
      '不同金属需要分开',
      '生锈严重会影响回收价值'
    ],
    '玻璃': [
      '破损玻璃需单独包装',
      '不接受特殊玻璃（如镜子、玻璃杯）',
      '有色玻璃与透明玻璃需分开'
    ],
    '电子产品': [
      '请确保已删除个人信息',
      '含有个人数据需专业处理',
      '破损严重的设备价值较低'
    ],
    '有害垃圾': [
      '切勿随意丢弃，污染环境',
      '必须送至专门回收点',
      '注意防止泄漏和损坏'
    ]
  }
  
  return categoryNotices[item.category] || [
    '保持物品清洁',
    '分类存放',
    '及时送至回收站'
  ]
}

const getRecycleValue = (item) => {
  const categoryValues = {
    '纸类': '回收1吨废纸可生产0.8吨再生纸，节约木材3立方米，相当于少砍17棵大树，节约用水100立方米。',
    '塑料': '回收1吨塑料瓶可获得0.7吨二级原料，节约石油资源，减少环境污染。1个塑料瓶在土壤中需要200年才能降解。',
    '金属': '回收1吨废钢铁可炼得0.9吨好钢，节约矿石2-3吨，节约标准煤0.4吨，减少大量废气、废水、废渣排放。',
    '玻璃': '回收1吨废玻璃可生产0.9吨再生玻璃，节约石英砂720公斤，少用纯碱250公斤，节约能源消耗。',
    '电子产品': '电子产品含有贵金属和稀有金属，回收利用可减少对自然资源的开采，同时避免有害物质污染环境。',
    '有害垃圾': '正确回收有害垃圾可以防止重金属和有毒物质污染土壤和水源，保护生态环境和人类健康。'
  }
  
  return categoryValues[item.category] || '回收利用可以节约资源，减少环境污染，为可持续发展做贡献。'
}

const handleImageError = (event) => {
  event.target.src = '/default-item.jpg'
}

// 生命周期
onMounted(() => {
  loadItems()
})
</script>

<style scoped>
.item-browse {
  padding: 0;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding: 20px 0;
}

.header-content h2 {
  margin: 0 0 8px 0;
  color: #333;
  font-size: 24px;
}

.header-content p {
  margin: 0;
  color: #666;
  font-size: 14px;
}

.filter-card {
  margin-bottom: 20px;
  border-radius: 8px;
}

.filters {
  display: flex;
  align-items: center;
  gap: 20px;
  flex-wrap: wrap;
}

.filter-group {
  display: flex;
  align-items: center;
  gap: 8px;
}

.filter-group label {
  font-size: 14px;
  color: #666;
  white-space: nowrap;
}

.items-section {
  margin-bottom: 20px;
}

.item-card {
  margin-bottom: 20px;
  border-radius: 12px;
  transition: all 0.3s ease;
  height: 100%;
}

.item-card:hover {
  transform: translateY(-4px);
  box-shadow: 0 8px 25px rgba(0, 0, 0, 0.15);
}

.item-image {
  position: relative;
  height: 180px;
  overflow: hidden;
  border-radius: 8px 8px 0 0;
  background: #f5f5f5;
}

.item-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.item-status {
  position: absolute;
  top: 8px;
  right: 8px;
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
  color: white;
}

.item-status.active {
  background: #67C23A;
}

.item-status.inactive {
  background: #F56C6C;
}

.item-info {
  padding: 16px;
}

.item-name {
  margin: 0 0 8px 0;
  font-size: 16px;
  font-weight: 600;
  color: #333;
}

.item-category {
  margin: 0 0 8px 0;
  font-size: 12px;
  color: #999;
}

.item-description {
  margin: 0 0 12px 0;
  font-size: 13px;
  color: #666;
  line-height: 1.4;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.item-price-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}

.price-section .price {
  font-size: 18px;
  font-weight: bold;
  color: #67C23A;
}

.price-section .unit {
  font-size: 12px;
  color: #999;
  margin-left: 2px;
}

.price-trend {
  display: flex;
  align-items: center;
  gap: 4px;
  font-size: 12px;
}

.price-trend .up {
  color: #67C23A;
}

.price-trend .down {
  color: #F56C6C;
}

.item-actions {
  display: flex;
  gap: 8px;
}

.item-actions .el-button {
  flex: 1;
}

.pagination-section {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

.recycle-guide {
  max-height: 600px;
  overflow-y: auto;
}

.guide-section {
  margin-bottom: 16px;
  border-radius: 8px;
}

.guide-section:last-child {
  margin-bottom: 0;
}

.section-title {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 16px;
  font-weight: 600;
  color: #333;
}

.guide-content {
  margin: 0;
  padding: 12px 0;
  color: #666;
  line-height: 1.6;
}

.guide-steps {
  padding: 8px 0;
}

.step-item {
  display: flex;
  align-items: flex-start;
  gap: 12px;
  margin-bottom: 12px;
}

.step-item:last-child {
  margin-bottom: 0;
}

.step-number {
  width: 28px;
  height: 28px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #409EFF;
  color: white;
  border-radius: 50%;
  font-weight: 600;
  font-size: 14px;
  flex-shrink: 0;
}

.step-content {
  flex: 1;
  padding-top: 4px;
  color: #666;
  line-height: 1.6;
}

.notice-list {
  margin: 0;
  padding-left: 20px;
  color: #666;
}

.notice-list li {
  margin-bottom: 8px;
  line-height: 1.6;
}

.notice-list li:last-child {
  margin-bottom: 0;
}

.recycle-value {
  padding: 8px 0;
}

.recycle-value p {
  margin: 0 0 16px 0;
  color: #666;
  line-height: 1.6;
}

.price-info {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 12px;
  background: #f5f7fa;
  border-radius: 6px;
}

.price-info span:first-child {
  color: #666;
}

.price-info .price {
  font-size: 18px;
  font-weight: bold;
  color: #67C23A;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .page-header {
    flex-direction: column;
    gap: 16px;
    align-items: flex-start;
  }
  
  .search-section {
    width: 100%;
  }
  
  .search-section .el-input {
    width: 100% !important;
  }
  
  .filters {
    flex-direction: column;
    align-items: flex-start;
    gap: 12px;
  }
  
  .filter-group {
    width: 100%;
    justify-content: space-between;
  }
}
</style>
